﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using MyLib.MyConnect.MSSQL;
using MyLib.MyUtility;
using System.Text;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.IO;
namespace MyChocCuoi.DB.Content
{
    public class NewsFacebookInfo
    {
        private static DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(NewsFacebookInfo));      

        [DataMember(Name = "url")]
        public string url { get; set; }

        [DataMember(Name = "normalized_url")]
        public string normalized_url { get; set; }

        [DataMember(Name = "share_count")]
        public int share_count { get; set; }
        
        [DataMember(Name = "like_count")]
        public int like_count { get; set; }

        [DataMember(Name = "comment_count")]
        public int comment_count { get; set; }

        [DataMember(Name = "total_count")]
        public int total_count { get; set; }

        [DataMember(Name = "commentsbox_count")]
        public int commentsbox_count { get; set; }

          [DataMember(Name = "comments_fbid")]
        public string comments_fbid { get; set; }

         [DataMember(Name = "click_count")]
        public int click_count { get; set; }

         public static NewsFacebookInfo Deserialize(string json)
         {
             if (string.IsNullOrEmpty(json))
             {
                 throw new ArgumentNullException("json");
             }

             return Deserialize(new MemoryStream(Encoding.UTF8.GetBytes(json)));
         }

         public static NewsFacebookInfo Deserialize(Stream jsonStream)
         {
             if (jsonStream == null)
             {
                 throw new ArgumentNullException("jsonStream");
             }

             return (NewsFacebookInfo)jsonSerializer.ReadObject(jsonStream);
         }

         public bool IsNull
         {
             get
             {
                 if (string.IsNullOrEmpty(url))
                     return true;
                 else
                     return false;
             }
         }

    }
    public class NewsObject
    {
        public int NewsID = 0;
        public int PID = 0;
        public int CateID = 0;
        public int TypeID = 0;
        public string Title = string.Empty;
        public string ResourceLink = string.Empty;
        public string Tag = string.Empty;
        public string Image = string.Empty;
        public string Embed = string.Empty;
        public int MemberID = 0;
        public string OpenID = string.Empty;
        public string MemberName = string.Empty;
        public DateTime CreateDate = DateTime.MinValue;
        public DateTime ModifyDate = DateTime.MinValue;
        public DateTime UpdateDate = DateTime.MinValue;
        public int ViewCount = 0;
        public int CommentCount = 0;
        public int ShareCount = 0;
        public int LikeCount = 0;
        public int FunnyCount = 0;
        public int DieCount = 0;
        public int StatusID = 0;
        public int Priority = 0;
        public bool IsNull
        {
            get
            {
                if (NewsID <= 0)
                    return true;
                else
                    return false;
            }
        }

        public static NewsObject Convert(DataTable mTable)
        {
            List<NewsObject> mList = new List<NewsObject>();
            mList = MyConvert.ConvertTable2Object<NewsObject>(mTable);
            if (mList.Count > 0)
            {
                return mList[0];
            }
            return new NewsObject();
        }
        public static List<NewsObject> ConvertList(DataTable mTable)
        {
            List<NewsObject> mList = new List<NewsObject>();
            mList = MyConvert.ConvertTable2Object<NewsObject>(mTable);
            return mList;
        }

        /// <summary>
        /// Lấy link của bài này
        /// </summary>
        /// <returns></returns>
        public string DetailLink()
        {
            if (IsNull)
                return MyConfig.Domain;
            return MyConfig.Domain + "/chi-tiet/" + MyText.CreateRewriteURL(Title)+"-"+ NewsID.ToString()+".html";
        }


        /// <summary>
        /// Lấy thống kê từ facebook cho tin bài dựa theo link
        /// </summary>
        /// <returns></returns>
        public NewsFacebookInfo GetFacebookInfo()
        {
            if (IsNull)
                return new NewsFacebookInfo();

            string format = "https://graph.facebook.com/fql?q=SELECT url, normalized_url, share_count, like_count, comment_count, total_count, commentsbox_count, comments_fbid, click_count FROM link_stat WHERE url=\"{0}\"";
            string Result = MyFile.ReadContentFromURL(string.Format(format, new string[] { DetailLink() }));

            Result = Result.Substring(9);
            Result = Result.Substring(0, Result.Length - 2);

            NewsFacebookInfo mFBInfo = NewsFacebookInfo.Deserialize(Result);

            return mFBInfo;
        }

        public bool SyncFacebookInfo(News mNews)
        {
            try
            {
                NewsFacebookInfo mFBInfo = GetFacebookInfo();
                ViewCount++;
                LikeCount = mFBInfo.like_count;
                CommentCount = mFBInfo.comment_count;
                ShareCount = mFBInfo.share_count;

                List<NewsObject> mList = new List<NewsObject>();
                mList.Add(this);
                DataTable mTable = MyConvert.ConvertObject2Table<NewsObject>(mList);
                mTable.TableName = "Child";
                DataSet mSet = new DataSet("Parent");
                mSet.Tables.Add(mTable);
                MyConvert.ConvertDateColumnToStringColumn(ref mSet);
                return mNews.Update(1, mSet.GetXml());
            }
            catch(Exception ex)
            {
                throw ex;
            }
        }
    }

    public class News
    {
        public enum Category
        {
            Nothing = 0,
            Funny = 1,
            Sad = 2,
            Both=3,
        }
        public enum NewsType
        {
            Nothing = 0,
            Image = 1,
            Video = 2,
        }
        public enum Status
        {
            Nothing = 0,
            Active = 1,
            Deactive = 2,
        }

        MyExecuteData mExec = new MyExecuteData();
        MyGetData mGet = new MyGetData();

        public DataSet CreateDataSet()
        {
            try
            {
                string[] mPara = { "Type" };
                string[] mValue = { "0" };
                DataSet mSet = mGet.GetDataSet("Sp_News_Select", mPara, mValue);

                if (mSet != null && mSet.Tables.Count >= 1)
                {
                    mSet.DataSetName = "Parent";
                    mSet.Tables[0].TableName = "Child";
                }
                return mSet;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public DataTable Select(int? Type, string Para_1)
        {
            try
            {
                string[] mpara = { "Type", "Para_1" };
                string[] mValue = { Type.ToString(), Para_1 };
                return mGet.GetDataTable("Sp_News_Select", mpara, mValue);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="Type">Type = 2:Lay theo status và ID (Para_1 = NewsID, Para_2 = StatusID</param>
        /// <param name="Para_1"></param>
        /// <param name="Para_2"></param>
        /// <returns></returns>
        public DataTable Select(int? Type, string Para_1, string Para_2)
        {
            try
            {
                string[] mpara = { "Type", "Para_1", "Para_2" };
                string[] mValue = { Type.ToString(), Para_1, Para_2 };
                return mGet.GetDataTable("Sp_News_Select", mpara, mValue);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public bool Update(int Type, string XMLContent)
        {
            try
            {
                string[] mpara = { "Type", "XMLContent" };
                string[] mValue = { Type.ToString(), XMLContent };
                if (mExec.ExecProcedure("Sp_News_Update", mpara, mValue) > 0)
                {
                    return true;
                }
                else
                {
                    return false;
                }

            }
            catch (SqlException ex)
            {
                throw ex;
            }
        }


        public bool Insert(int Type, string XMLContent)
        {
            try
            {
                string[] mpara = { "Type", "XMLContent" };
                string[] mValue = { Type.ToString(), XMLContent };

                if (mExec.ExecProcedure("Sp_News_Insert", mpara, mValue) > 0)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (SqlException ex)
            {
                throw ex;
            }
        }

        public DataTable InsertReturn(int Type, string XMLContent)
        {
            try
            {
                string[] mpara = { "Type", "XMLContent" };
                string[] mValue = { Type.ToString(), XMLContent };

                DataSet mSet = mGet.GetDataSet("Sp_News_Insert", mpara, mValue);

                return mSet.Tables[0];

            }
            catch (SqlException ex)
            {
                throw ex;
            }
            finally
            {
                mExec.UseTransction = false;
            }
        }

        public bool Delete(int Type, string XMLContent)
        {
            try
            {
                string[] mpara = { "Type", "XMLContent" };
                string[] mValue = { Type.ToString(), XMLContent };
                if (mExec.ExecProcedure("Sp_News_Delete", mpara, mValue) > 0)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (SqlException ex)
            {
                throw ex;
            }
        }

        public int TotalRow(int? Type, string SearchContent, Status StatusID, NewsType TypeID, int CateID)
        {
            try
            {
                string[] mPara = { "Type", "SearchContent", "StatusID", "TypeID", "CateID",  "IsTotalRow" };
                string[] mValue = { Type.ToString(), SearchContent, ((int)StatusID).ToString(), ((int)TypeID).ToString(), CateID.ToString(), true.ToString() };

                return (int)mGet.GetExecuteScalar("Sp_News_Search", mPara, mValue);
            }
            catch (SqlException ex)
            {
                throw ex;
            }
        }

        public DataTable Search(int? Type, int BeginRow, int EndRow, string SearchContent, Status StatusID, NewsType TypeID, int CateID, string ShortBy)
        {
            try
            {
                string[] mPara = { "Type", "BeginRow", "EndRow", "SearchContent", "StatusID", "TypeID", "CateID",  "ShortBy", "IsTotalRow" };
                string[] mValue = { Type.ToString(), BeginRow.ToString(), EndRow.ToString(), SearchContent, ((int)StatusID).ToString(), ((int)TypeID).ToString(), CateID.ToString(), ShortBy, false.ToString() };
                return mGet.GetDataTable("Sp_News_Search", mPara, mValue);

            }
            catch (SqlException ex)
            {
                throw ex;
            }
        }
    }
}
